//
//  TableViewController.swift
//  Reid
//
//  Created by Fizgrad Chen on 2022/4/30.
//

import UIKit

class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!
    
    var searchController: UISearchController!
    
    var place_dict: [String:[String:Any]]?
    var sortedArray: [Dictionary<String, [String : Any]>.Element]?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        self.tabBarItem.title = "详情"
        self.tabBarItem.image = UIImage(named: "detail")
        
        
        let url = Bundle.main.url(forResource: "data", withExtension: "plist")
        let placeDict = NSDictionary(contentsOf: url!)
        place_dict = placeDict as? [String:[String:Any]]
        let xib = UINib(nibName: "UItableTableViewCell", bundle: Bundle.main)
        tableView.register(xib, forCellReuseIdentifier: "cell")
        tableView.rowHeight = 140
        
        sortedArray = place_dict!.sorted(by:
                                            {(first, second) -> Bool in
            let firstnumofpeople = first.value["present"] as! Double
            let secondnumofpeople = second.value["present"] as! Double
            return firstnumofpeople < secondnumofpeople
        })
        
        initSearch()
    }

    @IBAction func buttonPressed(_ sender: UIBarButtonItem) {
        if sender.title == "按人流升序"
        {
            sortedArray = place_dict!.sorted(by:
                                                {(first, second) -> Bool in
                let firstnumofpeople = first.value["present"] as! Double
                let secondnumofpeople = second.value["present"] as! Double
                return firstnumofpeople < secondnumofpeople
            })
            tableView.reloadData()
        }
        if sender.title == "按人均用时升序"
        {
            sortedArray = place_dict!.sorted(by: {(first, second) -> Bool in
                let firstnumofpeople = first.value["present"] as! Double
                let firstnumofpeople10ago = first.value["10ago"] as! Double
                let secondnumofpeople = second.value["present"] as! Double
                let secondnumofpeople10ago = second.value["10ago"] as! Double
                return abs(firstnumofpeople - firstnumofpeople10ago) < abs(secondnumofpeople - secondnumofpeople10ago)
            })
            tableView.reloadData()
        }
    }
    // MARK: - Table view data source

    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return sortedArray!.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // Configure the cell...
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! UItableTableViewCell
        
        let numofpeople = sortedArray![indexPath.row].value["present"] as! Double
        let numofpeople10ago = sortedArray![indexPath.row].value["10ago"] as! Double
        let timeperson = abs(numofpeople - numofpeople10ago) / 10
        
        if numofpeople >= 200
        {
            cell.level.backgroundColor = .red
        }
        else if (numofpeople < 200 && numofpeople >= 150)
        {
            cell.level.backgroundColor = .yellow
        }
        else if (numofpeople < 150 && numofpeople >= 100)
        {
            cell.level.backgroundColor = .green
        }
        else
        {
            cell.level.backgroundColor = .blue
        }
        
        cell.timeperperason.text = String(format: "%1.1f", timeperson)+"分钟"
        cell.numofpeople.text = "\(numofpeople)人/分钟"
        cell.placeName.text = sortedArray![indexPath.row].key
        cell.mainImage.image = UIImage(named: sortedArray![indexPath.row].key)
        
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let detail = storyboard?.instantiateViewController(withIdentifier: "detail") as! detailViewController
        detail.count = sortedArray![indexPath.row].value["present"] as? Int
        detail.flow = sortedArray![indexPath.row].value["flow"] as? Double
        detail.time = sortedArray![indexPath.row].value["time"] as? Double
        detail.dist = sortedArray![indexPath.row].value["dist"] as? Double
        detail.englishName = sortedArray![indexPath.row].value["englishName"] as? String
        
        present(detail, animated: true, completion: nil)
    }
    
    	func initSearch()
    {
        let resultsController = SearchResultTableViewController()
        resultsController.allInfo = sortedArray
        
        searchController = UISearchController(searchResultsController: resultsController)
        let searchBar = searchController.searchBar
        searchBar.scopeButtonTitles = ["按地址查找"]
        searchBar.placeholder = "Enter a search item"
        searchBar.sizeToFit()
        tableView.tableHeaderView = searchBar
        searchController.searchResultsUpdater = resultsController
        self.definesPresentationContext = true
        
        
        let timeButton = UIBarButtonItem(title: "按人均核酸时间排序", style: .plain, target: self, action: nil)
        let items: [UIBarButtonItem] = [timeButton]
        let toolbar = UIToolbar()
        toolbar.setItems(items, animated: true)
        self.navigationController?.view.addSubview(toolbar)
         
    }
    
    override func viewWillAppear(_ animated: Bool) {
        tableView.reloadData()
    }
    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
